package com.mantru.iotpot.setting

import android.app.Dialog
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.media.AudioManager
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.SeekBar
import android.widget.TextView
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.mantru.iotpot.ApplicationClass
import com.mantru.iotpot.Begin.LoginActivity
import com.mantru.iotpot.R
import com.mantru.iotpot.Tools.LoadingDialogUtil
import com.mantru.iotpot.Util.SharePreUtil.getStringData
import com.mantru.iotpot.Util.ToastUtils
import com.mantru.iotpot.databinding.ActivitySettingBinding
import com.mantru.iotpot.eventbus.EventMessage
import com.mantru.iotpot.modbus.Common
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.json.JSONObject
import java.io.IOException


class SettingActivity : AppCompatActivity() {
    private val viewModel by viewModels<SettingViewModel>()
    private lateinit var binding: ActivitySettingBinding
    private var result: Boolean = false // 定义全局变量
    private var result_menu: Boolean = false // 定义全局变量
    private lateinit var ac: ApplicationClass // 声明 ApplicationClass 实例
    private var name: String = "" // 声明全局变量 name
    private lateinit var api_url: String // 声明全局变量 api_url
    private var isAppNeedUpgrade: Int = 0 // 声明全局变量 isAppNeedUpgrade
    private var newAppVersion: String = "" // 声明全局变量 newAppVersion
    private var AppFileUrl: String = "" // 声明全局变量 AppFileUrl
    private var isIapNeedUpgrade: Int = 0 // 声明全局变量 isIapNeedUpgrade
    private var newIapVersion: String = "" // 声明全局变量 newIapVersion
    private var IapFileUrl: String = "" // 声明全局变量 IapFileUrl
    private var ErrorGripper = 0 //0表示机械臂没有故障，1表示机械臂出现故障
    private val TAG = "SettingActivity"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        EventBus.getDefault().register(this)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_setting)
        binding.viewModel = viewModel // 绑定viewModel
        binding.lifecycleOwner = this // 允许 LiveData 自动更新 UI
        ac = application as ApplicationClass // 获取 ApplicationClass 实例
        name = ac.GetSQLData_Cleaning_Nozzle_GetNameList()
        Log.d("SettingActivity", "Name value: $name") // 打印 name 值用于调试
        api_url = "${Common.API_Server_Url}?txt_type=/potnew/init_data/&save_type=check_app_upgrade&device_id=${ac.activity_device_id}&app_version=${ac.APP_Version}"
        Log.d("SettingActivity", "api_url value: $api_url") // 打印 name 值用于调试
        result = ac.OilBoxIsHeat_GetValue()// 设置油罐加热 Switch 的状态
        result_menu = ac.GetSQLData_GetOrderBy()
        Log.d("SettingActivity", "Initial result value: $result") // 打印初始
        Log.d("SettingActivity", "Initial result_menu value: $result_menu") // 打印初始
        binding.switchOilHeat.isChecked = result
        binding.switchmenu.isChecked = result_menu
        //读取状态栏展示状态
        val barState = getStringData(ac, "barState")
        binding.statebarShowIcon.isChecked = !(barState.isNullOrEmpty() || barState == "false")
        //设置控件交互事件
        setContentAction()
        fetchApiData()//判断app是否有新的版本
        fetchIapData()//判断Iap是否有新的版本
    }

    //设置控件交互事件
    private fun setContentAction(){

        //返回按钮
        binding.settingBack.setOnClickListener{
            LoadingDialogUtil.showLoadingDialog(this@SettingActivity)
            finish()
        }

        //升级APP按钮
        binding.updateApp.setOnClickListener{
            if ( isAppNeedUpgrade == 1 ){
                binding.updateAppNeedUp.visibility = View.VISIBLE
                val intent = Intent(this@SettingActivity, UpgradeAppActivity::class.java)
                startActivity(intent)
            } else {
                binding.updateAppNeedUp.visibility = View.GONE
                //Toast.makeText(this@SettingActivity, "当前App无可升级的版本", Toast.LENGTH_SHORT).show()
                ToastUtils.show(this@SettingActivity, "当前App无可升级的版本")
            }
        }


        //调味料校准
        binding.jiaozhun.setOnClickListener{
            if (ac.gripper_position_value == 2){//机械臂抬起来
                val intent = Intent(this@SettingActivity, SeasoningCalibrationActivity::class.java)
                startActivity(intent)
            }else if (ac.gripper_position_value == 1){//机械臂放下
                if (ErrorGripper == 1){
                    val json_data = ac.GetSQLData_Calibration_List()
                    ShowCheakDialog(1)
                }else{
                    val intent = Intent(this@SettingActivity, SeasoningCalibrationActivity::class.java)
                    startActivity(intent)
                }
            }
        }

        //管路自助清洗
        binding.pieJiaozhun.setOnClickListener {
            if (ac.gripper_position_value == 2){//机械臂抬起来
                val intent = Intent(this@SettingActivity, PipelineSelfCleaningActivity::class.java)
                startActivity(intent)
            }else if (ac.gripper_position_value == 1){//机械臂放下
                if (ErrorGripper == 1){
                    val json_data = ac.GetSQLData_Calibration_List()
                    ShowCheakDialog(2)
                }else{
                    val intent = Intent(this@SettingActivity, PipelineSelfCleaningActivity::class.java)
                    startActivity(intent)
                }
            }
        }

        // 设置油罐加热 Switch 的点击事件
        binding.switchOilHeat.setOnCheckedChangeListener { _, isChecked ->
            result = isChecked
            Log.d("SettingActivity", "Updated result value: $result") // 打印更新后的 result 值
            ac.OilBoxIsHeat_SaveValue(result)
            // 显示Toast提示
            if (isChecked) {
                //Toast.makeText(this@SettingActivity, "油罐加热已开启", Toast.LENGTH_SHORT).show()
                ToastUtils.show(this@SettingActivity, "油罐加热已开启")
            } else {
                //Toast.makeText(this@SettingActivity, "油罐加热已关闭", Toast.LENGTH_SHORT).show()
                ToastUtils.show(this@SettingActivity, "油罐加热已关闭")
            }
        }

        binding.switchmenu.setOnCheckedChangeListener { buttonView, isChecked ->
            result_menu = isChecked
            Log.d("SettingActivity", "Updated result_menu value: $result_menu") // 打印更新后的 result_menu 值
            ac.SaveSQLData_SaveOrderBy(result_menu)
        }

        //调味料放置详情
        binding.seasoningDetails.setOnClickListener {
            val intent = Intent(this@SettingActivity, SetSeasoningCalibrationActivity::class.java)
            startActivity(intent)
        }

        //料管清洗
        if (!name.isNullOrEmpty()) {
            // 如果 name 不为空，设置点击事件并显示 liaoguan_need_up
            binding.liaoguan.setOnClickListener {
                val intent = Intent(this@SettingActivity, CleaningPipeActivity::class.java)
                startActivity(intent)
            }
            binding.liaoguanNeedUp.visibility = View.VISIBLE // 显示 liaoguan_need_up
        } else {
            // 如果 name 为空，显示 Toast 提示，并隐藏 liaoguan_need_up
            binding.liaoguan.setOnClickListener {
                //Toast.makeText(this@SettingActivity, "当前无可清洗的料管", Toast.LENGTH_SHORT).show()
                ToastUtils.show(this@SettingActivity, "当前无可清洗的料管")
            }
            Log.d("SettingActivity", "Name is empty, no click event set for liaoguan")
            binding.liaoguanNeedUp.visibility = View.GONE // 隐藏 liaoguan_need_up
        }

        //洗锅参数设置
        binding.washingSetting.setOnClickListener {
            val intent = Intent(this@SettingActivity, WashingSettingActivity::class.java)
            startActivity(intent)
        }

        //音量调节
        binding.voice.setOnClickListener{
            showVoiceDialog();
        }

        //关于本机
        binding.about.setOnClickListener {
            val intent = Intent(this@SettingActivity, AboutMeActivity::class.java)
            startActivity(intent)
        }

        //wifi连接
        binding.wifi.setOnClickListener {
            val intent = Intent(this@SettingActivity, WiFiActivity::class.java)
            startActivity(intent)
        }

        //IAP升级
        binding.updateIap.setOnClickListener {
            if (isIapNeedUpgrade == 1){//Iap需要升级
                binding.updateIapNeedUp.visibility = View.VISIBLE
                val intent = Intent(this@SettingActivity, UpgradeIapActivity::class.java)
                startActivity(intent)
            }else{
                binding.updateIapNeedUp.visibility = View.GONE
                //Toast.makeText(this@SettingActivity, "当前Iap无可升级的版本", Toast.LENGTH_SHORT).show()
                ToastUtils.show(this@SettingActivity, "当前Iap无可升级的版本")
            }
        }

        //导航栏开关
        binding.statebarShowIcon.setOnCheckedChangeListener { _, isChecked ->
            viewModel.showStateBar(isChecked)
        }

        //故障日志
        binding.appError.setOnClickListener {
            val intent = Intent(this@SettingActivity, FaultLogActivity::class.java)
            startActivity(intent)
        }

        //退出登录
        binding.appExit.setOnClickListener {
            showCleaningPipeDialog()
        }
    }

    //显示弹窗
    private fun showVoiceDialog() {
        val dialog = Dialog(this)
        dialog.setContentView(R.layout.voice_dialog)
        dialog.window?.setBackgroundDrawableResource(android.R.color.transparent)
        dialog.setCanceledOnTouchOutside(false)

        val seekBar = dialog.findViewById<SeekBar>(R.id.voice_seekbar)
        val closeBtn = dialog.findViewById<View>(R.id.dialog_voice_close)
        val voiceDialogText = dialog.findViewById<TextView>(R.id.voice_dialog_text)

        val audioManager = getSystemService(AUDIO_SERVICE) as AudioManager
        val maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)
        val currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)

        seekBar.max = maxVolume
        seekBar.progress = currentVolume

        // 更新文本显示当前音量
        voiceDialogText.text = "当前音量为: $currentVolume"

        seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0)
                // 更新文本显示当前音量
                voiceDialogText.text = "当前音量为: $progress"
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {}
            override fun onStopTrackingTouch(seekBar: SeekBar?) {}
        })

        closeBtn.setOnClickListener {
            audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, seekBar.progress, 0)
            dialog.dismiss()
        }

        dialog.show()
    }

    //判断App是否需要升级
    private fun fetchApiData() {
        val client = OkHttpClient()
        val request = Request.Builder()
            .url(api_url)
            .build()
        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                runOnUiThread {
                    //Toast.makeText(this@SettingActivity, "App版本信息请求失败: ${e.message}", Toast.LENGTH_SHORT).show()
                    ToastUtils.show(this@SettingActivity, "App版本信息请求失败: ${e.message}")
                }
            }
            override fun onResponse(call: Call, response: Response) {
                if (response.isSuccessful) {
                    val responseData = response.body?.string()
                    Log.d("SettingActivity", "API Response: $responseData")
                    try {
                        val jsonObject = JSONObject(responseData)
                        val success = jsonObject.getBoolean("success")
                        if (success) {
                            val upgradeData = jsonObject.getJSONObject("upgrade_data")
                            isAppNeedUpgrade = upgradeData.getInt("is_need_upgrade")
                            newAppVersion = upgradeData.getString("new_version")
                            AppFileUrl = upgradeData.getString("file_url")
                            Log.d("SettingActivity", "isAppNeedUpgrade: $isAppNeedUpgrade")
                            Log.d("SettingActivity", "newAppVersion: $newAppVersion")
                            Log.d("SettingActivity", "AppFileUrl: $AppFileUrl")
                            if ( isAppNeedUpgrade == 1 ){
                                runOnUiThread {
                                    binding.updateAppNeedUp.visibility = View.VISIBLE
                                }
                            } else {
                                runOnUiThread {
                                    binding.updateAppNeedUp.visibility = View.GONE
                                }
                            }
                        } else {
                            Log.d("SettingActivity", "获取json数据失败")
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                        Log.d("SettingActivity", "获取json数据失败,原因： ${e.message}")
                    }
                } else {
                    runOnUiThread {
                        //Toast.makeText(this@SettingActivity, "请求失败: ${response.code}", Toast.LENGTH_SHORT).show()
                        ToastUtils.show(this@SettingActivity, "请求失败: ${response.code}")
                    }
                }
            }
        })
    }

    //判断Iap是否需要升级
    private fun fetchIapData() {
        val url = "${Common.API_Server_Url}?txt_type=/potnew/init_data/&save_type=check_iap_upgrade&device_id=${ac.activity_device_id}" +
                "&iap_version=${ac.activity_software_version}"
        val client = OkHttpClient()
        val request = Request.Builder().url(url).build()
        client.newCall(request).enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                runOnUiThread {
                    //Toast.makeText(this@SettingActivity, "Iap版本信息请求失败，请检查网络连接", Toast.LENGTH_SHORT).show()
                    ToastUtils.show(this@SettingActivity, "Iap版本信息请求失败，请检查网络连接")
                }
            }

            override fun onResponse(call: Call, response: Response) {
                if (response.isSuccessful) {
                    val responseData = response.body?.string()
                    Log.d("SettingActivity", "API Response: $responseData")
                    try {
                        val jsonObject = JSONObject(responseData)
                        if (jsonObject.getBoolean("success")) {
                            val upgradeData = jsonObject.getJSONObject("upgrade_data")
                            isIapNeedUpgrade = upgradeData.getInt("is_need_upgrade")
                            newIapVersion = upgradeData.getString("new_version")
                            IapFileUrl = upgradeData.getString("file_url")
                            Log.d("SettingActivity", "isIapNeedUpgrade: $isIapNeedUpgrade")
                            Log.d("SettingActivity", "newIapVersion: $newIapVersion")
                            Log.d("SettingActivity", "IapFileUrl: $IapFileUrl")
                            runOnUiThread {
                                binding.updateIapNeedUp.visibility = if (isIapNeedUpgrade == 1) View.VISIBLE else View.GONE
                            }
                        } else {
                            Log.d("SettingActivity", "获取json数据失败")
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                        Log.d("SettingActivity", "获取json数据失败,原因： ${e.message}")
                    }
                } else {
                    runOnUiThread {
                        //Toast.makeText(this@SettingActivity, "请求失败: ${response.code}", Toast.LENGTH_SHORT).show()
                        ToastUtils.show(this@SettingActivity, "请求失败: ${response.code}")
                    }
                }
            }
        })
    }

    // 在SettingActivity中注册和注销广播接收器
    private val receiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            if (intent.action == "ACTION_CLOSE_LOADING_DIALOG") {
                LoadingDialogUtil.closeLoadingDialog()
            }
        }
    }

    override fun onStart() {
        super.onStart()
        LocalBroadcastManager.getInstance(this).registerReceiver(receiver, IntentFilter("ACTION_CLOSE_LOADING_DIALOG"))
    }

    override fun onStop() {
        super.onStop()
        LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver)
    }

    override fun onResume() {
        super.onResume()
        // 在界面渲染完成后发送广播关闭弹窗
        Handler(Looper.getMainLooper()).post {
            val intent = Intent("ACTION_CLOSE_LOADING_DIALOG")
            LocalBroadcastManager.getInstance(this@SettingActivity).sendBroadcast(intent)
        }
    }

    override fun onDestroy() {
        EventBus.getDefault().unregister(this)
        super.onDestroy()
    }

    //显示弹窗
    private fun showCleaningPipeDialog() {
        // 创建自定义对话框
        val dialog = Dialog(this)
        dialog.setContentView(R.layout.cleaning_pipe_dialog) // 设置对话框的布局

        val titl: TextView = dialog.findViewById(R.id.cleaning_pipe_dialog_title)
        val titl2: TextView = dialog.findViewById(R.id.cleaning_pipe_dialog_title2)
        val cancle: Button = dialog.findViewById(R.id.cleaning_pipe_dialog_cancle)
        val comfirm: Button = dialog.findViewById(R.id.cleaning_pipe_dialog_confirm)

        titl.text = "是否要退出当前账号？"
        titl2.visibility = View.VISIBLE
        titl2.text = "提示：退出账号会使创建的本地菜谱信息全部清空！"
        cancle.text = "取消"
        comfirm.text = "确认"

        cancle.setOnClickListener {
            dialog.dismiss() // 关闭弹窗
        }

        comfirm.setOnClickListener {
            val result = ac.APP_Logout()
            Log.d("SettingActivity", "result value: $result") // 打印 name 值用于调试
            if (result){
                val intent = Intent(this@SettingActivity, LoginActivity::class.java)
                startActivity(intent)
                dialog.dismiss()
                finish()
            }else{
                ToastUtils.show(this@SettingActivity, "退出登录账号失败！")
            }

        }

        // 关键代码：设置窗口背景透明
        dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))

        // 设置点击外部不可取消对话框
        dialog.setCanceledOnTouchOutside(false)

        // 显示对话框
        dialog.show()
    }

    private fun ShowCheakDialog(param: Int) {
        // 创建自定义对话框
        val dialog1 = Dialog(this)
        dialog1.setContentView(R.layout.manual_cheak_dialog) // 设置对话框的布局

        val stop: Button = dialog1.findViewById<Button>(R.id.manual_cheak_dialog_stop)
        val low: Button = dialog1.findViewById<Button>(R.id.manual_cheak_dialog_low)
        val rotate: Button = dialog1.findViewById<Button>(R.id.manual_cheak_dialog_rotate)

        stop.setOnClickListener { v: View? ->
            ac.Device_SendCommand_Gripper_Stop()
            ac.SaveLog("用户点击了炒菜爪手动寻位的停止按钮")
        }

        low.setOnClickListener { v: View? ->
            ac.Device_SendCommand_Gripper_Slow()
            ac.SaveLog("用户点击了炒菜爪手动寻位的低速按钮")
        }

        rotate.setOnClickListener { v: View? ->
            ac.Device_SendCommand_Gripper_OK()
            ac.SaveLog("用户点击了炒菜爪手动寻位的确认按钮")
            dialog1.dismiss()
            if (param == 1){//调味料校准
                val intent = Intent(this@SettingActivity, SeasoningCalibrationActivity::class.java)
                startActivity(intent)
            }else if (param == 2){//管路自助清洗
                val intent = Intent(this@SettingActivity, PipelineSelfCleaningActivity::class.java)
                startActivity(intent)
            }
        }
        // 关键代码：设置窗口背景透明
        dialog1.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))

        dialog1.setCanceledOnTouchOutside(false)

        // 显示对话框
        dialog1.show()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEventBusMessage(event: EventMessage) {
        if (event.id == EventMessage.MSG_ID_ErrorGripper) { //收到了机械臂出现故障的消息
            ErrorGripper = 1
            ac.SaveLog(TAG + " 界面接收到机械臂出现故障的事件")
        }
    }
}